import * as vscode from 'vscode';
import { DeepseekAPI } from './deepseekAPI';
import { 
    ChatHistoryManager, 
    ChatSession, 
    ChatMessage, 
    AssistantMessage, 
    UserMessage, 
    SystemMessage 
} from './chatHistory';
import { CodebaseAnalyzer } from './codebaseAnalyzer';

export class ChatProvider {
    private panel: vscode.WebviewPanel | undefined;
    private _view: vscode.WebviewView | undefined;
    private context: vscode.ExtensionContext;
    private deepseekAPI: DeepseekAPI;
    private messages: (AssistantMessage | UserMessage | SystemMessage)[] = [];
    private historyManager: ChatHistoryManager;
    private isGenerating: boolean = false;
    private currentController: AbortController | null = null;
    private currentSessionId: string | null = null;

    constructor(context: vscode.ExtensionContext, deepseekAPI: DeepseekAPI, historyManager: ChatHistoryManager) {
        this.context = context;
        this.deepseekAPI = deepseekAPI;
        this.historyManager = historyManager;
        // 初始化时添加系统消息作为默认上下文
        const systemMessage: SystemMessage = {
            role: 'system',
            content: '你是一个智能的编程助手，可以帮助用户解决编程相关的问题。'
        };
        this.messages = [systemMessage];
    }

    private async updateSessionList() {
        try {
            // 重新加载会话列表
            const sessions = await this.historyManager.loadSessions();
            const sessionData = sessions.map(s => ({
                id: s.id,
                title: s.title,
                updatedAt: s.updatedAt
            }));

            console.log('Updating session list:', sessionData); // 添加日志

            // 更新面板视图
            if (this.panel?.webview) {
                this.panel.webview.postMessage({
                    command: 'updateSessions',
                    sessions: sessionData
                });
            }

            // 更新侧边栏视图
            if (this._view?.webview) {
                this._view.webview.postMessage({
                    command: 'updateSessions',
                    sessions: sessionData
                });
            }

            // 强制刷新当前会话
            if (this.currentSessionId) {
                await this.loadSession(this.currentSessionId);
            }
        } catch (error) {
            console.error('Error updating session list:', error);
        }
    }

    public async show() {
        try {
            if (this.panel) {
                this.panel.reveal();
            } else {
                console.log('Creating new webview panel');
                this.panel = vscode.window.createWebviewPanel(
                    'deepseekChat',
                    'DeepSeek Chat',
                    vscode.ViewColumn.Two,
                    {
                        enableScripts: true,
                        retainContextWhenHidden: true  // 添加这个选项保持上下文
                    }
                );

                // 加载最近的会话历史
                const sessions = await this.historyManager.loadSessions();
                if (sessions.length > 0) {
                    const currentSession = sessions[sessions.length - 1];
                    await this.loadSession(currentSession.id);
                } else {
                    await this.historyManager.createNewSession();
                }

                this.panel.webview.html = this.getWebviewContent();
                this.panel.webview.onDidReceiveMessage(
                    async message => {
                        console.log('Received message in panel:', message);
                        try {
                            switch (message.command) {
                                case 'sendMessage':
                                    await this.handleMessage(message.text, this.panel?.webview, message.model);
                                    break;
                                case 'newSession':
                                    console.log('Creating new session');
                                    await this.historyManager.createNewSession();
                                    await this.updateSessionList();
                                    this.messages = [{
                                        role: 'system',
                                        content: '你是一个智能的编程助手，可以帮助用户解决编程相关的问题。'
                                    }];
                                    if (this.panel) {
                                        this.panel.webview.postMessage({
                                            command: 'clearMessages'
                                        });
                                    }
                                    break;
                                case 'switchSession':
                                    await this.loadSession(message.sessionId);
                                    break;
                                case 'deleteSession':
                                    await this.handleDeleteSession(message.sessionId, this.panel!.webview);
                                    break;
                                case 'renameSession':
                                    await this.historyManager.renameSession(message.sessionId, message.title);
                                    await this.updateSessionList();
                                    break;
                                case 'stopGeneration':
                                    if (this.currentController) {
                                        this.currentController.abort();
                                    }
                                    break;
                                case 'regenerateMessage':
                                    const messageIndex = message.messageIndex;
                                    if (messageIndex >= 0 && messageIndex < this.messages.length) {
                                        // 删除从这条消息开始的所有后续消息
                                        this.messages = this.messages.slice(0, messageIndex * 2 + 1);
                                        // 重新发送最后一条用户消息
                                        await this.handleMessage(this.messages[this.messages.length - 1].content);
                                    }
                                    break;
                            }
                        } catch (error) {
                            console.error('Error handling panel message:', error);
                            this.panel?.webview.postMessage({
                                command: 'showError',
                                message: '操作失败：' + (error instanceof Error ? error.message : '未知错误')
                            });
                        }
                    },
                    undefined,
                    this.context.subscriptions
                );

                // 更新会话列表
                await this.updateSessionList();

                this.panel.onDidDispose(
                    () => {
                        this.panel = undefined;
                    },
                    null,
                    this.context.subscriptions
                );
            }
        } catch (error) {
            console.error('Error showing chat panel:', error);
            vscode.window.showErrorMessage('Failed to open chat panel');
        }
    }

    private async loadSession(sessionId: string) {
        try {
            const session = await this.historyManager.loadSession(sessionId);
            if (session) {
                this.currentSessionId = session.id;
                const systemMessage: SystemMessage = {
                    role: 'system',
                    content: '你是一个智能的编程助手，可以帮助用户解决编程相关的问题。'
                };

                // 确保会话消息包含正确的类型
                const sessionMessages = session.messages.map(msg => {
                    if (msg.role === 'assistant') {
                        return msg as AssistantMessage;
                    } else if (msg.role === 'user') {
                        return msg as UserMessage;
                    }
                    return msg as SystemMessage;
                });

                this.messages = [
                    systemMessage,
                    ...sessionMessages
                ];

                // 更新 UI
                if (this._view?.webview) {
                    this._view.webview.postMessage({
                        command: 'clearMessages'
                    });

                    // 重新显示所有消息
                    for (const message of sessionMessages) {
                        this._view.webview.postMessage({
                            command: 'addMessage',
                            message: message.content,
                            isUser: message.role === 'user',
                            reasoning: message.role === 'assistant' ? 
                                (message as AssistantMessage).reasoning_content : 
                                undefined
                        });
                    }
                }
            }
        } catch (error) {
            console.error('Error loading session:', error);
            throw error;
        }
    }

    private async handleMessage(text: string, webview?: vscode.Webview, model?: string) {
        console.log('handleMessage called with:', { text, webviewType: webview ? 'provided' : 'default' });
        const targetWebview = webview || this._view?.webview || this.panel?.webview;
        console.log('Target webview resolved to:', 
            targetWebview === this._view?.webview ? 'sidebar' : 
            targetWebview === this.panel?.webview ? 'panel' : 
            'unknown');

        if (!targetWebview) {
            console.error('No target webview found');
            return;
        }

        try {
            if (this.isGenerating) {
                console.log('Already generating, skipping...');
                return;
            }

            this.isGenerating = true;
            this.currentController = new AbortController();

            // 先添加用户消息
            if (targetWebview) {
                console.log('Adding user message to webview');
                targetWebview.postMessage({
                    command: 'addMessage',
                    message: text,
                    isUser: true
                });
            }

            // 添加用户消息到上下文并保存
            const userMessage: UserMessage = {
                role: 'user',
                content: text
            };
            this.messages.push(userMessage);
            await this.historyManager.addMessage(userMessage);

            // 添加空的 AI 消息占位
            if (targetWebview) {
                console.log('Adding empty AI message placeholder');
                targetWebview.postMessage({
                    command: 'addMessage',
                    message: '',
                    isUser: false,
                    isStreaming: true
                });
            }

            let responseContent = '';
            let reasoningContent = '';
            let currentResponse = '';

            try {
                const selectedModel = model || vscode.workspace.getConfiguration('deepseek').get('model') || 'deepseek-chat';
                console.log('Using model:', selectedModel);

                // 开始流式输出
                await this.deepseekAPI.chatStream(
                    this.messages,
                    (content, type) => {
                        console.log('Received stream chunk:', { type, contentLength: content.length });
                        if (type === 'reasoning') {
                            reasoningContent += content;
                            currentResponse = reasoningContent;
                        } else {
                            responseContent += content;
                            currentResponse = responseContent;
                        }
                        
                        if (targetWebview) {
                            console.log('Sending stream update to webview:', { 
                                type, 
                                contentLength: currentResponse.length 
                            });
                            targetWebview.postMessage({
                                command: 'updateStreamMessage',
                                content: currentResponse,
                                type: type || 'response'
                            });
                        }
                    },
                    this.currentController.signal,
                    selectedModel
                );

                console.log('Stream completed, saving response');
                // 流式输出完成后，保存 AI 响应
                const assistantMessage: AssistantMessage = {
                    role: 'assistant',
                    content: responseContent,
                    ...(reasoningContent && { reasoning_content: reasoningContent })
                };
                this.messages.push(assistantMessage);
                await this.historyManager.addMessage(assistantMessage);

                // 更新会话列表
                await this.updateSessionList();

                // 移除流式输出标记
                if (targetWebview) {
                    console.log('Sending finishStreaming command');
                    targetWebview.postMessage({
                        command: 'finishStreaming'
                    });
                }

            } catch (error) {
                console.error('Error during chat stream:', error);
                if (error instanceof Error && error.name === 'AbortError') {
                    console.log('Stream was aborted');
                    if (targetWebview) {
                        targetWebview.postMessage({
                            command: 'showInfo',
                            message: '已停止生成'
                        });
                    }
                    return;
                }
                throw error;
            }
        } finally {
            console.log('Finishing message handling');
            this.isGenerating = false;
            if (targetWebview) {
                targetWebview.postMessage({
                    command: 'updateGenerating',
                    isGenerating: false
                });
            }
        }
    }

    private async handleDeleteSession(sessionId: string, webview: vscode.Webview) {
        try {
            console.log('Deleting session:', sessionId);
            // 删除会话
            await this.historyManager.deleteSession(sessionId);
            
            // 清除当前会话的上下文
            if (sessionId === this.currentSessionId) {
                console.log('Clearing current session context');
                const systemMessage: SystemMessage = {
                    role: 'system',
                    content: '你是一个智能的编程助手，可以帮助用户解决编程相关的问题。'
                };
                this.messages = [systemMessage];
                this.currentSessionId = null;
                
                // 获取剩余会话
                const sessions = await this.historyManager.loadSessions();
                console.log('Remaining sessions:', sessions.length);
                
                if (sessions.length === 0) {
                    // 如果没有会话了，创建新会话
                    const newSession = await this.historyManager.createNewSession();
                    this.currentSessionId = newSession.id;
                    // 更新 UI
                    webview.postMessage({
                        command: 'clearMessages'
                    });
                    webview.postMessage({
                        command: 'updateActiveSession',
                        sessionId: newSession.id
                    });
                } else {
                    // 切换到最新的会话
                    const latestSession = sessions[sessions.length - 1];
                    this.currentSessionId = latestSession.id;
                    await this.loadSession(latestSession.id);
                }
            }
            
            // 强制更新会话列表
            await this.updateSessionList();
            
            // 通知 webview 更新完成
            webview.postMessage({
                command: 'sessionDeleted',
                sessionId: sessionId
            });
            
            console.log('Session deletion completed');
        } catch (error) {
            console.error('Error deleting session:', error);
            webview.postMessage({
                command: 'showError',
                message: '删除会话失败：' + (error instanceof Error ? error.message : '未知错误')
            });
        }
    }

    private getWebviewContent() {
        return `
            <!DOCTYPE html>
            <html>
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <style>
                        body {
                            margin: 0;
                            padding: 0;
                            height: 100vh;
                            overflow: hidden;
                        }
                        
                        .main-container {
                            display: flex;
                            height: 100vh;
                            overflow: hidden;
                        }
                        
                        .sidebar {
                            width: 250px;
                            height: 100%;
                            display: flex;
                            flex-direction: column;
                            border-right: 1px solid var(--vscode-panel-border);
                            background: var(--vscode-sideBar-background);
                        }
                        
                        #newChatButton {
                            margin: 10px;
                            background: var(--vscode-button-secondaryBackground);
                            color: var(--vscode-button-secondaryForeground);
                            border: none;
                            padding: 4px 12px;
                            border-radius: 2px;
                        }
                        
                        #newChatButton:hover {
                            background: var(--vscode-button-secondaryHoverBackground);
                        }
                        
                        .chat-list {
                            flex: 1;
                            overflow-y: auto;
                            padding: 0;
                            margin: 0;
                            list-style: none;
                        }
                        
                        .chat-container {
                            flex: 1;
                            display: flex;
                            flex-direction: column;
                            height: 100%;
                        }
                        
                        #messages {
                            flex: 1;
                            overflow-y: auto;
                            padding: 20px 0;
                        }
                        
                        .chat-item {
                            position: relative;
                            padding: 8px 32px 8px 10px;
                            cursor: pointer;
                            display: flex;
                            align-items: center;
                        }
                        
                        .chat-item-actions {
                            position: absolute;
                            right: 8px;
                            display: none;
                            gap: 4px;
                            align-items: center;
                        }
                        
                        .chat-item:hover .chat-item-actions {
                            display: flex;
                        }
                        
                        .action-button {
                            padding: 4px;
                            background: none;
                            border: none;
                            cursor: pointer;
                            opacity: 0.7;
                        }
                        
                        .action-button:hover {
                            opacity: 1;
                        }

                        .input-container {
                            display: flex;
                            flex-direction: column;
                            gap: 8px;
                            padding: 16px;
                            background: var(--vscode-editor-background);
                            border-top: 1px solid var(--vscode-editor-lineHighlightBorder);
                            position: sticky;
                            bottom: 0;
                        }

                        .input-row {
                            display: flex;
                            gap: 8px;
                            align-items: flex-start;
                        }

                        .input-group {
                            flex: 1;
                            display: flex;
                            flex-direction: column;
                            gap: 8px;
                            min-width: 0; /* 防止flex子项溢出 */
                        }

                        #messageInput {
                            flex: 1;
                            padding: 8px 12px;
                            border: 1px solid var(--vscode-input-border);
                            background: var(--vscode-input-background);
                            color: var(--vscode-input-foreground);
                            border-radius: 4px;
                            min-height: 40px;
                            max-height: 200px;
                            resize: vertical;
                            font-family: var(--vscode-font-family);
                            font-size: 13px;
                            line-height: 1.5;
                        }

                        #messageInput:focus {
                            outline: none;
                            border-color: var(--vscode-focusBorder);
                        }

                        .button-group {
                            display: flex;
                            gap: 8px;
                            align-items: flex-start;
                        }

                        .model-selector {
                            padding: 4px 8px;
                            border: 1px solid var(--vscode-dropdown-border);
                            background: var(--vscode-dropdown-background);
                            color: var(--vscode-dropdown-foreground);
                            border-radius: 4px;
                            font-size: 12px;
                            height: 28px;
                            min-width: 150px; /* 增加最小宽度 */
                        }

                        .model-selector:hover {
                            background: var(--vscode-dropdown-listBackground);
                        }

                        .model-selector:focus {
                            outline: none;
                            border-color: var(--vscode-focusBorder);
                        }

                        .model-group {
                            display: flex;
                            flex-direction: column;
                            gap: 4px;
                        }

                        .model-label {
                            font-size: 12px;
                            color: var(--vscode-descriptionForeground);
                        }

                        #sendButton {
                            padding: 6px 12px;
                            height: 28px;
                            min-width: 80px;
                            white-space: nowrap;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                        }

                        .stop-button {
                            padding: 6px 12px;
                            height: 28px;
                            min-width: 80px;
                            background: var(--vscode-button-secondaryBackground);
                            color: var(--vscode-button-secondaryForeground);
                            display: none;
                        }

                        @media (max-width: 480px) {
                            .input-container {
                                padding: 8px;
                            }

                            .button-group {
                                flex-direction: column;
                                width: 80px;
                            }

                            #sendButton, .stop-button {
                                width: 100%;
                            }
                        }

                        .message-hint {
                            color: var(--vscode-descriptionForeground);
                            font-style: italic;
                            margin: 10px 0;
                            padding: 10px;
                            border-radius: 4px;
                            background: var(--vscode-editor-lineHighlightBackground);
                        }
                        .error-message {
                            color: var(--vscode-errorForeground);
                            background-color: var(--vscode-errorBackground);
                            padding: 8px;
                            margin: 8px 0;
                            border-radius: 4px;
                        }
                        .action-button.delete-btn {
                            background: #d32f2f;
                            color: white;
                            padding: 2px 8px;
                            border-radius: 3px;
                            font-size: 12px;
                            border: none;
                            cursor: pointer;
                            transition: background-color 0.2s;
                        }

                        .action-button.delete-btn:hover {
                            background: #b71c1c;
                        }

                        .message {
                            display: flex;
                            gap: 12px;
                            margin: 20px 0;
                            padding: 0 16px;
                        }

                        .message-avatar {
                            width: 32px;
                            height: 32px;
                            border-radius: 50%;
                            flex-shrink: 0;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            font-size: 16px;
                            font-weight: bold;
                        }

                        .message-content {
                            flex: 1;
                            max-width: 80%;
                            padding: 12px 16px;
                            border-radius: 8px;
                            font-size: 14px;
                            line-height: 1.5;
                        }

                        .message-header {
                            font-size: 12px;
                            margin-bottom: 4px;
                            color: var(--vscode-descriptionForeground);
                        }

                        .user-message {
                            flex-direction: row-reverse;
                        }

                        .user-message .message-avatar {
                            background: #4a9eff;
                            color: white;
                        }

                        .user-message .message-content {
                            background: #4a9eff33;
                            margin-left: auto;
                        }

                        .assistant-message {
                            flex-direction: row;
                        }

                        .assistant-message .message-avatar {
                            background: #0f9d58;
                            color: white;
                        }

                        .assistant-message .message-content {
                            background: var(--vscode-editor-lineHighlightBackground);
                            margin-right: auto;
                        }

                        .message pre {
                            background: var(--vscode-editor-background);
                            padding: 12px;
                            border-radius: 4px;
                            overflow-x: auto;
                            margin: 8px 0;
                        }

                        .message code {
                            font-family: var(--vscode-editor-font-family);
                            font-size: 13px;
                        }

                        .reasoning-content {
                            background: #2d2d2d;
                            color: #b3b3b3;
                            padding: 10px;
                            margin: 5px 0;
                            border-left: 3px solid #666;
                            font-family: monospace;
                        }
                    </style>
                </head>
                <body>
                    <div class="main-container">
                        <div class="sidebar">
                            <button id="newChatButton" class="button">新建会话</button>
                            <ul id="chatList" class="chat-list"></ul>
                        </div>
                        <div class="chat-container">
                            <div class="message-hint">
                                提示: 输入 @codebase 分析当前工作区的所有代码文件
                            </div>
                            <div id="messages"></div>
                            <div class="input-container">
                                <div class="input-row">
                                    <div class="input-group">
                                        <textarea 
                                            id="messageInput" 
                                            placeholder="输入消息，按 Enter 发送，Shift+Enter 换行..."
                                            rows="1"
                                            onInput="this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px';"
                                        ></textarea>
                                    </div>
                                    <div class="button-group">
                                        <div class="model-group">
                                            <label for="modelSelector" class="model-label">选择模型</label>
                                            <select id="modelSelector" class="model-selector">
                                                <optgroup label="对话模型">
                                                    <option value="deepseek-chat">DeepSeek-V3 (deepseek-chat)</option>
                                                </optgroup>
                                                <optgroup label="推理模型">
                                                    <option value="deepseek-reasoner">DeepSeek-R1 (deepseek-reasoner)</option>
                                                </optgroup>
                                            </select>
                                        </div>
                                        <button id="sendButton">发送</button>
                                        <button id="stop-button" class="stop-button">停止生成</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <script>
                        const vscode = acquireVsCodeApi();
                        const messagesContainer = document.getElementById('messages');
                        const messageInput = document.getElementById('messageInput');
                        const sendButton = document.getElementById('sendButton');
                        const stopButton = document.getElementById('stop-button');
                        const chatList = document.getElementById('chatList');
                        let currentSessionId = null;
                        let isGenerating = false;
                        let currentAssistantMessage = null;

                        // 添加消息到界面
                        function addMessage(content, isUser) {
                            const messageDiv = document.createElement('div');
                            messageDiv.className = \`message \${isUser ? 'user-message' : 'assistant-message'}\`;

                            // 添加头像
                            const avatarDiv = document.createElement('div');
                            avatarDiv.className = 'message-avatar';
                            avatarDiv.textContent = isUser ? '👤' : 'AI';

                            // 添加消息内容容器
                            const contentContainer = document.createElement('div');
                            contentContainer.className = 'message-content';

                            // 添加消息头部（显示用户名）
                            const headerDiv = document.createElement('div');
                            headerDiv.className = 'message-header';
                            headerDiv.textContent = isUser ? '你' : 'DeepSeek Assistant';
                            contentContainer.appendChild(headerDiv);

                            // 添加消息文本
                            const textDiv = document.createElement('div');
                            textDiv.className = 'message-text';
                            textDiv.textContent = content;
                            contentContainer.appendChild(textDiv);

                            messageDiv.appendChild(avatarDiv);
                            messageDiv.appendChild(contentContainer);
                            messagesContainer.appendChild(messageDiv);
                            messagesContainer.scrollTop = messagesContainer.scrollHeight;

                            if (!isUser) {
                                currentAssistantMessage = contentContainer;
                            }
                        }

                        // 修改消息更新处理
                        function updateLastAssistantMessage(content, type) {
                            if (!currentAssistantMessage) {
                                const messageDiv = document.createElement('div');
                                messageDiv.className = 'message assistant-message';

                                const avatarDiv = document.createElement('div');
                                avatarDiv.className = 'message-avatar';
                                avatarDiv.textContent = 'AI';

                                currentAssistantMessage = document.createElement('div');
                                currentAssistantMessage.className = 'message-content';

                                const headerDiv = document.createElement('div');
                                headerDiv.className = 'message-header';
                                headerDiv.textContent = 'DeepSeek Assistant';
                                currentAssistantMessage.appendChild(headerDiv);

                                const textDiv = document.createElement('div');
                                textDiv.className = 'message-text';
                                currentAssistantMessage.appendChild(textDiv);

                                messageDiv.appendChild(avatarDiv);
                                messageDiv.appendChild(currentAssistantMessage);
                                messagesContainer.appendChild(messageDiv);
                            }

                            const messageText = currentAssistantMessage.querySelector('.message-text');
                            
                            if (type === 'reasoning') {
                                // 创建或更新思维链内容
                                let reasoningDiv = messageText.querySelector('.reasoning-content');
                                if (!reasoningDiv) {
                                    reasoningDiv = document.createElement('div');
                                    reasoningDiv.className = 'reasoning-content';
                                    messageText.appendChild(reasoningDiv);
                                }
                                reasoningDiv.textContent = content;
                            } else {
                                // 更新正常响应内容
                                let responseDiv = messageText.querySelector('.response-content');
                                if (!responseDiv) {
                                    responseDiv = document.createElement('div');
                                    responseDiv.className = 'response-content';
                                    messageText.appendChild(responseDiv);
                                }
                                responseDiv.textContent = content;
                            }
                            
                            messagesContainer.scrollTop = messagesContainer.scrollHeight;
                        }

                        // 修改删除按钮的处理逻辑
                        function updateChatList(sessions) {
                            const chatList = document.querySelector('.chat-list');
                            chatList.innerHTML = '';
                            
                            sessions.forEach(session => {
                                const li = document.createElement('li');
                                li.className = 'chat-item' + (session.id === currentSessionId ? ' active' : '');
                                li.dataset.id = session.id;
                                
                                const titleSpan = document.createElement('span');
                                titleSpan.className = 'chat-item-title';
                                titleSpan.textContent = session.title || '新会话';
                                li.appendChild(titleSpan);
                                
                                const actionsDiv = document.createElement('div');
                                actionsDiv.className = 'chat-item-actions';
                                
                                const deleteButton = document.createElement('button');
                                deleteButton.className = 'action-button delete-btn';
                                deleteButton.title = '删除会话';
                                deleteButton.textContent = '删除';
                                deleteButton.style.cssText = 'background: #d32f2f; color: white; padding: 2px 8px; border-radius: 3px; font-size: 12px;';
                                deleteButton.onmouseover = function() {
                                    this.style.background = '#b71c1c';
                                };
                                deleteButton.onmouseout = function() {
                                    this.style.background = '#d32f2f';
                                };
                                
                                // 修改删除按钮的点击事件处理
                                deleteButton.onclick = function(e) {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    
                                    // 直接发送删除命令，不使用 confirm
                                    vscode.postMessage({ 
                                        command: 'deleteSession',
                                        sessionId: session.id 
                                    });
                                    
                                    // 添加视觉反馈
                                    li.style.opacity = '0.5';
                                    li.style.pointerEvents = 'none';
                                };
                                
                                actionsDiv.appendChild(deleteButton);
                                li.appendChild(actionsDiv);
                                
                                // 会话点击事件保持不变
                                li.onclick = function(e) {
                                    if (!e.target.closest('.action-button')) {
                                        currentSessionId = session.id;
                                        vscode.postMessage({
                                            command: 'switchSession',
                                            sessionId: session.id
                                        });
                                        document.querySelectorAll('.chat-item').forEach(item => {
                                            item.classList.remove('active');
                                        });
                                        li.classList.add('active');
                                    }
                                };
                                
                                chatList.appendChild(li);
                            });
                        }

                        // 更新活动会话
                        function updateActiveSession(sessionId) {
                            currentSessionId = sessionId;
                            document.querySelectorAll('.chat-item').forEach(item => {
                                item.classList.remove('active');
                                if (item.dataset.id === sessionId) {
                                    item.classList.add('active');
                                }
                            });
                        }

                        // 事件监听
                        window.addEventListener('message', event => {
                            const message = event.data;
                            console.log('Received message from extension:', message);
                            
                            try {
                                switch (message.command) {
                                    case 'addMessage':
                                        addMessage(message.message, message.isUser);
                                        break;
                                    case 'updateResponse':
                                        updateLastAssistantMessage(message.content, message.type);
                                        break;
                                    case 'clearMessages':
                                        messagesContainer.innerHTML = '';
                                        currentAssistantMessage = null;
                                        break;
                                    case 'updateGenerating':
                                        isGenerating = message.isGenerating;
                                        stopButton.style.display = isGenerating ? 'block' : 'none';
                                        if (!isGenerating) {
                                            currentAssistantMessage = null;
                                        }
                                        break;
                                    case 'showError':
                                        console.error('Error from extension:', message.message);
                                        const errorDiv = document.createElement('div');
                                        errorDiv.className = 'error-message';
                                        errorDiv.textContent = message.message;
                                        messagesContainer.appendChild(errorDiv);
                                        break;
                                    case 'updateSessions':
                                        console.log('Updating sessions list:', message.sessions);
                                        updateChatList(message.sessions);
                                        break;
                                    case 'loadMessages':
                                        messagesContainer.innerHTML = '';
                                        currentAssistantMessage = null;
                                        if (message.messages && Array.isArray(message.messages)) {
                                            message.messages.forEach(msg => {
                                                addMessage(msg.content, msg.role === 'user');
                                            });
                                        }
                                        break;
                                    case 'updateActiveSession':
                                        updateActiveSession(message.sessionId);
                                        break;
                                    case 'sessionDeleted':
                                        console.log('Session deleted:', message.sessionId);
                                        // 删除对应的 DOM 元素
                                        const deletedItem = document.querySelector(\`chat-item[data-id="\${message.sessionId}"]\`);
                                        if (deletedItem) {
                                            deletedItem.style.animation = 'fadeOut 0.3s';
                                            setTimeout(() => {
                                                deletedItem.remove();
                                                // 如果删除的是当前会话，清空消息区域
                                                if (message.sessionId === currentSessionId) {
                                                    messagesContainer.innerHTML = '';
                                                }
                                            }, 300);
                                        }
                                        break;
                                }
                            } catch (error) {
                                console.error('Error handling message:', error);
                                const errorDiv = document.createElement('div');
                                errorDiv.className = 'error-message';
                                errorDiv.textContent = '操作失败，请重试';
                                messagesContainer.appendChild(errorDiv);
                            }
                        });

                        // 发送消息时包含模型选择
                        function sendMessage() {
                            const text = messageInput.value.trim();
                            const model = document.getElementById('modelSelector').value;
                            if (text) {
                                console.log('Sending message:', text, 'with model:', model);
                                vscode.postMessage({
                                    command: 'sendMessage',
                                    text: text,
                                    model: model
                                });
                                messageInput.value = '';
                            }
                        }

                        // 模型说明
                        const modelDescriptions = {
                            'deepseek-chat': 'DeepSeek-V3 是最新的通用对话模型，适合日常对话和代码相关任务。',
                            'deepseek-reasoner': 'DeepSeek-R1 是专门的推理模型，适合需要复杂推理的任务。'
                        };

                        // 模型选择器事件处理
                        const modelSelector = document.getElementById('modelSelector');
                        const modelHint = document.querySelector('.model-hint');
                        const hintContent = document.querySelector('.hint-content');

                        modelSelector.addEventListener('change', function() {
                            const selectedModel = this.value;
                            // 保存选择
                            vscode.setState({ 
                                ...vscode.getState(), 
                                model: selectedModel 
                            });
                            
                            // 显示模型说明
                            if (modelDescriptions[selectedModel]) {
                                hintContent.textContent = modelDescriptions[selectedModel];
                                modelHint.style.display = 'block';
                                setTimeout(() => {
                                    modelHint.style.display = 'none';
                                }, 3000);
                            }
                        });

                        // 加载保存的模型选择
                        const savedModel = vscode.getState()?.model || 'deepseek-chat';
                        modelSelector.value = savedModel;

                        // 初始化时触发一次 change 事件
                        modelSelector.dispatchEvent(new Event('change'));

                        // 事件监听
                        sendButton.addEventListener('click', sendMessage);
                        
                        messageInput.addEventListener('keydown', (e) => {
                            if (e.key === 'Enter' && !e.shiftKey) {
                                e.preventDefault();
                                sendMessage();
                            }
                        });

                        document.getElementById('newChatButton').addEventListener('click', () => {
                            vscode.postMessage({ command: 'newSession' });
                        });
                        
                        stopButton.addEventListener('click', () => {
                            vscode.postMessage({ command: 'stopGeneration' });
                        });

                        // 添加一些 CSS 动画
                        const styleContent = \`
                            <style>
                                @keyframes fadeOut {
                                    from { opacity: 1; }
                                    to { opacity: 0; }
                                }
                                
                                .chat-item {
                                    transition: all 0.3s ease;
                                }
                                
                                .error-message {
                                    animation: fadeIn 0.3s;
                                }
                                
                                @keyframes fadeIn {
                                    from { opacity: 0; }
                                    to { opacity: 1; }
                                }
                            </style>
                        \`;

                        // 将样式添加到 head 中
                        document.head.insertAdjacentHTML('beforeend', styleContent);

                        // 输入框自适应高度
                        messageInput.addEventListener('input', function() {
                            this.style.height = 'auto';
                            this.style.height = (this.scrollHeight) + 'px';
                        });

                        // 限制最大高度
                        messageInput.addEventListener('input', function() {
                            if (this.scrollHeight > 200) {
                                this.style.overflowY = 'auto';
                            } else {
                                this.style.overflowY = 'hidden';
                            }
                        });

                        // 处理窗口大小变化
                        window.addEventListener('resize', function() {
                            messageInput.style.height = 'auto';
                            messageInput.style.height = (messageInput.scrollHeight) + 'px';
                        });
                    </script>
                </body>
            </html>
        `;
    }

    public async showInView(webviewView: vscode.WebviewView) {
        console.log('showInView called');
        this._view = webviewView;
        try {
            // 设置 webview 选项
            webviewView.webview.options = {
                enableScripts: true,
                localResourceRoots: [
                    this.context.extensionUri
                ]
            };

            // 设置 HTML 内容
            webviewView.webview.html = this.getWebviewContent();

            // 加载最近的会话历史
            const sessions = await this.historyManager.loadSessions();
            if (sessions.length > 0) {
                const currentSession = sessions[sessions.length - 1];
                await this.loadSession(currentSession.id);
            } else {
                const newSession = await this.historyManager.createNewSession();
                // 确保新会话在 UI 中显示
                webviewView.webview.postMessage({
                    command: 'updateSessions',
                    sessions: [newSession].map(s => ({
                        id: s.id,
                        title: s.title,
                        updatedAt: s.updatedAt
                    }))
                });
            }

            // 注册消息处理
            webviewView.webview.onDidReceiveMessage(
                async message => {
                    console.log('Received message in view:', message);
                    try {
                        switch (message.command) {
                            case 'sendMessage':
                                await this.handleMessage(message.text, webviewView.webview, message.model);
                                break;
                            case 'newSession':
                                const newSession = await this.historyManager.createNewSession();
                                this.messages = [{
                                    role: 'system',
                                    content: '你是一个智能的编程助手，可以帮助用户解决编程相关的问题。'
                                }];
                                webviewView.webview.postMessage({
                                    command: 'clearMessages'
                                });
                                // 更新会话列表
                                await this.updateSessionList();
                                // 设置新会话为活动会话
                                webviewView.webview.postMessage({
                                    command: 'updateActiveSession',
                                    sessionId: newSession.id
                                });
                                break;
                            case 'switchSession':
                                await this.loadSession(message.sessionId);
                                break;
                            case 'deleteSession':
                                await this.handleDeleteSession(message.sessionId, webviewView.webview);
                                break;
                            case 'renameSession':
                                await this.historyManager.renameSession(message.sessionId, message.title);
                                await this.updateSessionList();
                                break;
                            case 'stopGeneration':
                                if (this.currentController) {
                                    this.currentController.abort();
                                }
                                break;
                        }
                    } catch (error) {
                        console.error('Error handling view message:', error);
                    }
                },
                undefined,
                this.context.subscriptions
            );

            // 更新会话列表
            await this.updateSessionList();
        } catch (error) {
            console.error('Error in showInView:', error);
            throw error;
        }
    }
} 